import axios from 'axios'
import {
  BASE_URL,
  TIMEOUT
} from './config'
import useMainStore from '@/stores/modules/main'
import {
  showToast
} from 'vant';
import 'vant/es/toast/style';
const mainStore = useMainStore()
class HYRequest {
  constructor(baseURL, timeout = 10000) {
    this.instance = axios.create({
      baseURL:import.meta.env.VITE_BASE_URL,//该地址由所在的环境决定，目前我写了测试、开发、生产的相关地址
      timeout
    })

    this.instance.interceptors.request.use(config => {
      mainStore.isLoading = true
      let userinfo = localStorage.getItem('userinfo1')
      let token = userinfo ? JSON.parse(userinfo).token : ''
      // console.log(token, 'token')
      if (token) {
        config.headers.token = token
      }
      return config
    }, err => {
      return err
    })
    this.instance.interceptors.response.use(res => {
      mainStore.isLoading = false
      // console.log(res,11)
      return res
    }, err => {
      mainStore.isLoading = false
      return err
    })
  }

  request(config) {
    // mainStore.isLoading = true
    // console.log(config)
    return new Promise((resolve, reject) => {
      this.instance.request(config).then(res => {
        // console.log(res,22)
        if(res.code&&res.response.status ===401){
          showToast('请登录后操作!');
        }
        else if (res.data.code === 0) {
          if(res.data.msg == 'code失效'){
            resolve(res.data)
            return
          }
          showToast(res.data.msg);
        }
        else if (res.data.code === 200) {
          resolve(res.data)
        }
        else if (res.data.code === 401) {
          showToast(res.data.msg);
        }else{
          showToast('服务器错误');
        }
        // mainStore.isLoading = false
      }).catch(err => {
        // console.log(err,33)
        reject(err)
        showToast('服务器错误');
        // mainStore.isLoading = false
      })
    })
  }

  get(config) {
    return this.request({
      ...config,
      method: "get"
    })
  }

  post(config) {
    return this.request({
      ...config,
      method: "post"
    })
  }
}

export default new HYRequest(BASE_URL, TIMEOUT)